<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>AUTOX.JS截图</title>
    <!-- 引入 Element UI 的样式 -->
    <link rel="stylesheet" href="https://unpkg.com/element-ui/lib/theme-chalk/index.css">
    <style>
        body {
            margin: 0;
            padding: 0;
            background: #f1f1f1;
        }
        .screenshot-container {
            max-width: 1200px;
            margin: 0 auto;
            background: #fff;
            border-radius: 4px;
            box-shadow: 0 2px 12px 0 rgba(0,0,0,0.1);
        }
        .image-container {
            position: relative;
            width: 100%;
            background-color: #000;
            overflow: hidden;
        }
        .preview-image {
            position: relative;
            width: 100%;
            height: 0;
            background-position: center;
            background-repeat: no-repeat;
            background-size: contain;
        }
        .selection-box {
            position: absolute;
            border: 2px solid #409EFF;
            background-color: rgba(64, 158, 255, 0.1);
            cursor: move;
        }
        .resize-handle {
            position: absolute;
            width: 8px;
            height: 8px;
            background-color: #fff;
            border: 2px solid #409EFF;
            border-radius: 50%;
        }
        .handle-nw { cursor: nw-resize; top: -6px; left: -6px; }
        .handle-n  { cursor: n-resize;  top: -6px; left: 50%; transform: translateX(-50%); }
        .handle-ne { cursor: ne-resize; top: -6px; right: -6px; }
        .handle-w  { cursor: w-resize;  top: 50%; left: -6px; transform: translateY(-50%); }
        .handle-e  { cursor: e-resize;  top: 50%; right: -6px; transform: translateY(-50%); }
        .handle-sw { cursor: sw-resize; bottom: -6px; left: -6px; }
        .handle-s  { cursor: s-resize;  bottom: -6px; left: 50%; transform: translateX(-50%); }
        .handle-se { cursor: se-resize; bottom: -6px; right: -6px; }
        .coordinates {
            position: fixed;
            bottom: 20px;
            left: 20px;
            background: rgba(0, 0, 0, 0.7);
            color: white;
            padding: 10px;
            border-radius: 4px;
            font-family: monospace;
        }
        .header {
            padding: 15px 20px;
            border-bottom: 1px solid #ebeef5;
            display: flex;
            justify-content: space-between;
            align-items: center;
        }
        .header-title {
            font-size: 16px;
            color: #303133;
        }
        .mode-switch {
            margin: 10px 0;
            padding: 0 20px;
        }
        .color-textarea {
            margin: 10px 20px;
        }
    </style>
</head>
<body>
    <div id="app">
        <div class="screenshot-container">
            <div class="header">
                <span class="header-title">IMG</span>
                <div>
                    <el-radio-group v-model="mode" size="small">
                        <el-radio-button label="select">选区</el-radio-button>
                        <el-radio-button label="color">取色</el-radio-button>
                    </el-radio-group>
                    <el-button 
                        type="primary" 
                        size="small" 
                        icon="el-icon-camera"
                        :loading="loading"
                        @click="handleRefresh">
                        重新截图
                    </el-button>
                    <el-button 
                        type="success" 
                        size="small"
                        :disabled="!selection"
                        @click="copyCoordinates">
                        复制坐标
                    </el-button>
                    <el-button 
                        type="warning" 
                        size="small"
                        icon="el-icon-delete"
                        :disabled="!colorPoints"
                        @click="clearColorPoints">
                        清除取色
                    </el-button>
                </div>
            </div>

            <div class="color-textarea">
                <el-input
                    type="textarea"
                    v-model="colorPoints"
                    :rows="2"
                    :autosize="{ minRows: 2 }"
                    :placeholder="mode === 'color' ? '点击图片获取颜色...' : '切换到取色模式...'"
                    readonly>
                </el-input>
            </div>

            <div v-loading="loading" class="image-container">
                <div class="preview-image" 
                     :style="imageStyle"
                     @mousedown="handleMouseDown"
                     @click="handleClick"
                     ref="previewImage">
                    <div v-if="mode === 'select' && (selecting || selection)" 
                         class="selection-box"
                         :style="selectionStyle">
                        <div class="resize-handle handle-nw" data-handle="nw" @mousedown.stop="startResize($event, 'nw')"></div>
                        <div class="resize-handle handle-n"  data-handle="n"  @mousedown.stop="startResize($event, 'n')"></div>
                        <div class="resize-handle handle-ne" data-handle="ne" @mousedown.stop="startResize($event, 'ne')"></div>
                        <div class="resize-handle handle-w"  data-handle="w"  @mousedown.stop="startResize($event, 'w')"></div>
                        <div class="resize-handle handle-e"  data-handle="e"  @mousedown.stop="startResize($event, 'e')"></div>
                        <div class="resize-handle handle-sw" data-handle="sw" @mousedown.stop="startResize($event, 'sw')"></div>
                        <div class="resize-handle handle-s"  data-handle="s"  @mousedown.stop="startResize($event, 's')"></div>
                        <div class="resize-handle handle-se" data-handle="se" @mousedown.stop="startResize($event, 'se')"></div>
                    </div>
                </div>
            </div>
        </div>

        <div v-if="mode === 'select' && (selection || selecting)" class="coordinates">
            [{{ getCoordinatesText() }}]
        </div>
    </div>

    <!-- 引入 Vue -->
    <script src="https://unpkg.com/vue@2/dist/vue.js"></script>
    <!-- 引入 Element UI -->
    <script src="https://unpkg.com/element-ui/lib/index.js"></script>
    <script>
        const vscode = acquireVsCodeApi();
        
        new Vue({
            el: '#app',
            data() {
                return {
                    loading: false,
                    imageUrl: '',
                    selecting: false,
                    selectionStart: null,
                    selection: null,
                    currentPos: null,
                    imageWidth: 0,
                    imageHeight: 0,
                    containerWidth: 0,
                    mode: 'select',
                    colorPoints: '',
                    imageElement: null,
                    isDragging: false,
                    isResizing: false,
                    resizeHandle: null,
                    dragStartPos: null,
                    originalSelection: null
                }
            },
            computed: {
                imageStyle() {
                    if (!this.imageWidth || !this.imageHeight) return {};
                    const ratio = this.imageHeight / this.imageWidth;
                    return {
                        paddingBottom: `${ratio * 100}%`,
                        backgroundImage: `url(${this.imageUrl})`,
                        pointerEvents: this.loading ? 'none' : 'auto'
                    };
                },
                selectionStyle() {
                    if (!this.selecting && !this.selection) return {};
                    
                    const rect = this.getSelectionRect();
                    return {
                        left: rect.left + 'px',
                        top: rect.top + 'px',
                        width: rect.width + 'px',
                        height: rect.height + 'px'
                    };
                }
            },
            methods: {
                handleRefresh() {
                    this.loading = true;
                    this.selection = null;
                    vscode.postMessage({ type: 'refresh' });
                },
                loadImage() {
                    this.imageElement = new Image();
                    this.imageElement.onload = () => {
                        this.imageWidth = this.imageElement.width;
                        this.imageHeight = this.imageElement.height;
                        this.loading = false;
                    };
                    this.imageElement.src = this.imageUrl;
                },
                startSelection(e) {
                    if (this.mode !== 'select') return;
                    
                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const startX = ((e.clientX - rect.left) / rect.width) * 100;
                    const startY = ((e.clientY - rect.top) / rect.height) * 100;
                    
                    this.selecting = true;
                    this.selection = {
                        startX: startX,
                        startY: startY,
                        endX: startX,
                        endY: startY
                    };

                    // 添加全局事件监听
                    document.addEventListener('mousemove', this.updateSelection);
                    document.addEventListener('mouseup', this.endSelection);
                },
                updateSelection(e) {
                    if (!this.selecting) return;
                    
                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const currentX = ((e.clientX - rect.left) / rect.width) * 100;
                    const currentY = ((e.clientY - rect.top) / rect.height) * 100;
                    
                    this.selection.endX = currentX;
                    this.selection.endY = currentY;
                },
                endSelection(e) {
                    if (!this.selecting) return;

                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const endX = ((e.clientX - rect.left) / rect.width) * 100;
                    const endY = ((e.clientY - rect.top) / rect.height) * 100;
                    
                    // 计算选区宽高（像素值）
                    const width = Math.abs(endX - this.selection.startX) * rect.width / 100;
                    const height = Math.abs(endY - this.selection.startY) * rect.height / 100;
                    
                    if (width < 20 || height < 20) {
                        // 如果选区太小，复制起始点坐标（百分比）
                        const text = `${(this.selection.startX / 100).toFixed(4)}, ${(this.selection.startY / 100).toFixed(4)}`;
                        navigator.clipboard.writeText(text);
                        this.$message({
                            message: '已复制起始点坐标: ' + text,
                            type: 'success',
                            showClose: true,
                            duration: 500
                        });
                        this.selection = null;
                    } else {
                        // 正常完成选区
                        this.selection = {
                            startX: Math.min(this.selection.startX, endX),
                            startY: Math.min(this.selection.startY, endY),
                            endX: Math.max(this.selection.startX, endX),
                            endY: Math.max(this.selection.startY, endY)
                        };

                        // 计算并显示百分比坐标
                        const percentageCoords = [
                            (this.selection.startX / 100).toFixed(4),
                            (this.selection.startY / 100).toFixed(4),
                            (this.selection.endX / 100).toFixed(4),
                            (this.selection.endY / 100).toFixed(4)
                        ].join(', ');

                        // 自动复制选区坐标到剪贴板
                        navigator.clipboard.writeText(percentageCoords);
                        this.$message({
                            message: '已复制选区坐标: ' + percentageCoords,
                            type: 'success',
                            showClose: true,
                            duration: 500
                        });

                        console.log("选区坐标 (百分比):", percentageCoords);
                    }
                    
                    this.selecting = false;
                    // 移除全局事件监听
                    document.removeEventListener('mousemove', this.updateSelection);
                    document.removeEventListener('mouseup', this.endSelection);
                },
                getSelectionRect() {
                    if (!this.selecting && !this.selection) return {};
                    
                    const start = this.selectionStart;
                    const current = this.currentPos;
                    
                    if (this.selection) {
                        const rect = this.$refs.previewImage.getBoundingClientRect();
                        return {
                            left: (this.selection.startX * rect.width) / 100,
                            top: (this.selection.startY * rect.height) / 100,
                            width: ((this.selection.endX - this.selection.startX) * rect.width) / 100,
                            height: ((this.selection.endY - this.selection.startY) * rect.height) / 100
                        };
                    }
                    
                    return {
                        left: Math.min(start.x, current.x),
                        top: Math.min(start.y, current.y),
                        width: Math.abs(current.x - start.x),
                        height: Math.abs(current.y - start.y)
                    };
                },
                copyCoordinates() {
                    if (!this.selection && !this.selecting) return;
                    
                    const text = `[${this.getCoordinatesText()}]`;
                    
                    navigator.clipboard.writeText(text).then(() => {
                        this.showMessage('坐标已复制到剪贴板');
                    });
                },
                getCoordinatesText() {
                    if (this.selecting && this.currentPos) {
                        const rect = this.$refs.previewImage.getBoundingClientRect();
                        const startX = (this.selectionStart.x / rect.width) * 100;
                        const startY = (this.selectionStart.y / rect.height) * 100;
                        const endX = (this.currentPos.x / rect.width) * 100;
                        const endY = (this.currentPos.y / rect.height) * 100;
                        
                        const coords = [
                            Math.min(startX, endX) / 100,
                            Math.min(startY, endY) / 100,
                            Math.max(startX, endX) / 100,
                            Math.max(startY, endY) / 100
                        ].map(n => n.toFixed(4));
                        
                        return coords.join(',');
                    }
                    
                    if (this.selection) {
                        return [
                            this.selection.startX / 100,
                            this.selection.startY / 100,
                            this.selection.endX / 100,
                            this.selection.endY / 100
                        ].map(n => n.toFixed(4)).join(',');
                    }
                    
                    return '';
                },
                handleMouseDown(e) {
                    if (this.mode === 'select') {
                        this.startSelection(e);
                    }
                },
                handleClick(e) {
                    if (this.mode === 'color') {
                        this.getColorAtPoint(e);
                    }
                },
                getColorAtPoint(e) {
                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const x = e.clientX - rect.left;
                    const y = e.clientY - rect.top;
                    
                    // 创建 canvas 来获取图片像素
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    canvas.width = this.imageWidth;
                    canvas.height = this.imageHeight;
                    
                    // 在 canvas 上绘制图片
                    ctx.drawImage(this.imageElement, 0, 0);
                    
                    // 计算实际图片上的坐标（像素坐标）
                    const scaleX = this.imageWidth / rect.width;
                    const scaleY = this.imageHeight / rect.height;
                    const imageX = Math.floor(x * scaleX);
                    const imageY = Math.floor(y * scaleY);
                    
                    // 获取像素数据
                    const pixel = ctx.getImageData(imageX, imageY, 1, 1).data;
                    
                    // 转换为16进制颜色
                    const color = '#' + 
                        ('0' + pixel[0].toString(16)).slice(-2) +
                        ('0' + pixel[1].toString(16)).slice(-2) +
                        ('0' + pixel[2].toString(16)).slice(-2);
                    
                    // 计算百分比坐标
                    const percentageX = (x / rect.width).toFixed(4);  // 保留四位小数
                    const percentageY = (y / rect.height).toFixed(4);  // 保留四位小数
                    
                    // 添加到颜色点信息
                    const pointInfo = `${percentageX}, ${percentageY}`;  // 格式化为 [0.5, 0.6123]
                    this.colorPoints = this.colorPoints ? this.colorPoints + pointInfo : pointInfo;
                },
                clearColorPoints() {
                    this.colorPoints = '';
                    this.showMessage('已清除所有取色记录');
                },
                showMessage(message, type = 'success') {
                    this.$message({
                        message,
                        type,
                        showClose: true,     // 显示关闭按钮
                        duration: 600,      // 3秒后自动关闭
                        offset: 60,          // 距离顶部的偏移量
                        position: 'top-right' // 显示在右上角
                    });
                },
                startDrag(e) {
                    if (this.selection && !this.selecting) {
                        this.isDragging = true;
                        this.dragStartPos = {
                            x: e.clientX,
                            y: e.clientY,
                            selection: { ...this.selection }
                        };
                        
                        // 添加全局事件监听
                        document.addEventListener('mousemove', this.handleDrag);
                        document.addEventListener('mouseup', this.endDrag);
                    }
                },
                handleDrag(e) {
                    if (!this.isDragging) return;
                    
                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const deltaX = ((e.clientX - this.dragStartPos.x) / rect.width) * 100;
                    const deltaY = ((e.clientY - this.dragStartPos.y) / rect.height) * 100;
                    
                    this.selection = {
                        startX: this.dragStartPos.selection.startX + deltaX,
                        startY: this.dragStartPos.selection.startY + deltaY,
                        endX: this.dragStartPos.selection.endX + deltaX,
                        endY: this.dragStartPos.selection.endY + deltaY
                    };
                },
                endDrag() {
                    this.isDragging = false;
                    document.removeEventListener('mousemove', this.handleDrag);
                    document.removeEventListener('mouseup', this.endDrag);
                },
                startResize(e, handle) {
                    this.isResizing = true;
                    this.resizeHandle = handle;
                    this.originalSelection = { ...this.selection };
                    this.dragStartPos = {
                        x: e.clientX,
                        y: e.clientY
                    };
                    
                    document.addEventListener('mousemove', this.handleResize);
                    document.addEventListener('mouseup', this.endResize);
                },
                handleResize(e) {
                    if (!this.isResizing) return;
                    
                    const rect = this.$refs.previewImage.getBoundingClientRect();
                    const deltaX = ((e.clientX - this.dragStartPos.x) / rect.width) * 100;
                    const deltaY = ((e.clientY - this.dragStartPos.y) / rect.height) * 100;
                    
                    const newSelection = { ...this.originalSelection };
                    
                    // 完善所有控制点的处理
                    switch (this.resizeHandle) {
                        case 'nw':  // 左上
                            newSelection.startX += deltaX;
                            newSelection.startY += deltaY;
                            break;
                        case 'n':   // 上
                            newSelection.startY += deltaY;
                            break;
                        case 'ne':  // 右上
                            newSelection.endX += deltaX;
                            newSelection.startY += deltaY;
                            break;
                        case 'w':   // 左
                            newSelection.startX += deltaX;
                            break;
                        case 'e':   // 右
                            newSelection.endX += deltaX;
                            break;
                        case 'sw':  // 左下
                            newSelection.startX += deltaX;
                            newSelection.endY += deltaY;
                            break;
                        case 's':   // 下
                            newSelection.endY += deltaY;
                            break;
                        case 'se':  // 右下
                            newSelection.endX += deltaX;
                            newSelection.endY += deltaY;
                            break;
                    }
                    
                    // 确保选区不会反转
                    const finalSelection = {
                        startX: Math.min(newSelection.startX, newSelection.endX),
                        startY: Math.min(newSelection.startY, newSelection.endY),
                        endX: Math.max(newSelection.startX, newSelection.endX),
                        endY: Math.max(newSelection.startY, newSelection.endY)
                    };
                    
                    // 更新选区
                    this.selection = finalSelection;
                },
                endResize() {
                    this.isResizing = false;
                    document.removeEventListener('mousemove', this.handleResize);
                    document.removeEventListener('mouseup', this.endResize);
                }
            },
            mounted() {
                window.addEventListener('message', event => {
                    const message = event.data;
                    if (message.type === 'screenshot') {
                        this.imageUrl = message.data;
                        this.selection = null;
                        this.loading = false;
                        this.loadImage();
                    } else if (message.type === 'error') {
                        this.loading = false;
                        this.$message.error(message.message || '截图失败');
                    }
                });
            }
        })
    </script>
</body>
</html> 